<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      #calendar {
        width: 420px;
        display: flex;
        flex-wrap: wrap;
        border: 1px solid;
      }
      #calendar > div {
        width: 60px;
        height: 60px;
        box-sizing: border-box;
        border: 1px solid;
        display: flex;
        justify-content: center;
        align-items: center;
      }
    </style>
  </head>
  <body>
    <div id="calendar">
      <div>一</div>
      <div>二</div>
      <div>三</div>
      <div>四</div>
      <div>五</div>
      <div>六</div>
      <div>日</div>
    </div>
    <script>
      function calendar(node, y, m) {
        // 1 根据参数，获取日期对象
        // 2 获取参数m月份的最后一天
        const days = new Date(y, m, 0).getDate();
        // 4 获取当前参数月的1号是星期几
        const week = new Date(y, m - 1, 1).getDay() || 7;
        // 6 获取上个月的最后一天，结合星期计算日期
        const lastDays = new Date(y, m - 1, 0).getDate();

        // 7 获取当前参数月最后一天的星期
        const lastWeek = new Date(y, m, 0).getDay();

        let str = "";
        // 5 根据当前参数月的星期生成日历单元
        for (let i = week - 2; i >= 0; i--) {
          str += `<div>${lastDays - i}</div>`;
        }
        // 3 根据最后一天生成日历单元
        for (let i = 1; i <= days; i++) {
          str += `<div>${i}</div>`;
        }
        // 8 根据当前月的最后一天星期，填充单元格
        for (let i = 1; i <= 7 - lastWeek; i++) {
          str += `<div>${i}</div>`;
        }

        node.innerHTML += str;
      }
      calendar(document.getElementById("calendar"), 2023, 11);
    </script>
  </body>
</html>
